package com.gdut.simple.view.activity.explore;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import com.gdut.simple.R;
import com.gdut.simple.common.ShareUtils;
import com.gdut.simple.common.ToastUtils;
import com.gdut.simple.contract.HotPickContract;
import com.gdut.simple.data.entity.Favorites;
import com.gdut.simple.data.entity.News;
import com.gdut.simple.data.entity.User;
import com.gdut.simple.presenter.HotPickPresenter;
import com.gdut.simple.view.activity.user.FavoritesActivity;
import com.gdut.simple.view.activity.WebActivity;
import com.gdut.simple.view.adapter.HotPickAdapter;
import com.gdut.simple.view.adapter.base.AbsRecyclerAdapter;
import com.gdut.simple.view.basic.AbsBasicActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bmob.v3.BmobUser;
import rx.functions.Action1;
import rx.functions.Func1;

public class HotPickActivity extends AbsBasicActivity implements HotPickContract.View {

    @BindView(R.id.id_toolbar)
    Toolbar mToolbar;
    @BindView(R.id.id_item_list_view)
    RecyclerView mHotPickListView;
    @BindView(R.id.id_swipe_refresh_layout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    private HotPickAdapter mHotPickAdapter;
    private List<News> mHotPickList;
    private String type;
    private int mCurrentPage = 1;
    private HotPickContract.Presenter mHotPickPresenter;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_hot_pick);
        ButterKnife.bind(this);
        new HotPickPresenter(this);
        initToolbar();
        initRefreshLayout();
        initRecyclerView();
    }

    private void initToolbar() {
        mToolbar.setTitle(R.string.nav_hot_pick);
        setSupportActionBar(mToolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    finish();
                }
            });
        }
    }

    private void initRefreshLayout() {
        mSwipeRefreshLayout.setColorSchemeColors(ContextCompat.getColor(this, R.color.colorPrimaryDark),
                ContextCompat.getColor(this, R.color.colorPrimary),
                ContextCompat.getColor(this, R.color.colorPrimaryDark));
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mHotPickPresenter.refresh();
            }
        });
    }

    private void initRecyclerView() {
        mHotPickListView.setLayoutManager(new LinearLayoutManager(this));
        mHotPickListView.setItemAnimator(new DefaultItemAnimator());
        mHotPickList = new ArrayList<>();
        mHotPickAdapter = new HotPickAdapter(this, mHotPickList);
        mHotPickListView.setAdapter(mHotPickAdapter);
        mHotPickAdapter.setOnItemClickListener(new AbsRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                Intent intent = new Intent(HotPickActivity.this, WebActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("type", "热门精选");
                bundle.putString("url", mHotPickList.get(position).getUrl());
                bundle.putString("title", mHotPickList.get(position).getTitle());
                intent.putExtras(bundle);
                startActivity(intent);
            }

            @Override
            public boolean onLongClick(View view, int position) {
                showChoiceDialog(position);
                return true;
            }
        });
        mHotPickListView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItem = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
                int totalItemCount = recyclerView.getLayoutManager().getItemCount();
                if (lastVisibleItem >= totalItemCount - 1 && dy > 0) {
                    mHotPickPresenter.loadMore(++mCurrentPage);
                }
            }
        });
    }

    private void showChoiceDialog(final int position) {
        View view = LayoutInflater.from(this).inflate(R.layout.layout_dialog_single_choice, new LinearLayout(this), false);
        AlertDialog.Builder builder = new AlertDialog.Builder(this).setView(view);
        final Dialog dialog = builder.create();
        view.findViewById(R.id.id_action_collect).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                collect(mHotPickList.get(position).getTitle(), mHotPickList.get(position).getUrl(), "热门精选");
            }
        });
        view.findViewById(R.id.id_action_share).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ShareUtils.share(HotPickActivity.this, mHotPickList.get(position).getTitle(), mHotPickList.get(position).getUrl());
                dialog.dismiss();
            }
        });
        Button button = (Button) view.findViewById(R.id.id_action_search);
        button.setText("搜索 \"" + mHotPickList.get(position).getDescription() + "\"");
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(HotPickActivity.this, HotPickSearchActivity.class);
                intent.putExtra("src", mHotPickList.get(position).getDescription());
                startActivity(intent);
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void collect(String title, String url, String type) {
        final Favorites favorites = new Favorites();
        favorites.setTitle(title);
        favorites.setUrl(url);
        favorites.setType(type);
        favorites.setUser(BmobUser.getCurrentUser(User.class));
        favorites.saveObservable()
                .onErrorReturn(new Func1<Throwable, String>() {
                    @Override
                    public String call(Throwable throwable) {
                        return null;
                    }
                })
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        if (s == null) {
                            ToastUtils.showShort(getApplicationContext(), "error");
                            return;
                        }
                        Snackbar.make(mHotPickListView, "收藏成功", Snackbar.LENGTH_LONG)
                                .setAction("查看收藏夹", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        startActivity(new Intent(HotPickActivity.this, FavoritesActivity.class));
                                    }
                                })
                                .show();
                    }
                });
    }

    @Override
    protected void loadData() {
        mHotPickPresenter.refresh();
    }

    @Override
    public List<News> getItemList() {
        return mHotPickList;
    }

    @Override
    public String getType() {
        return type;
    }

    @Override
    public void reset() {
        mCurrentPage = 1;
    }

    @Override
    public void refreshList() {
        if (mHotPickAdapter != null) {
            mHotPickAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void showRefreshProgress() {
        if (mSwipeRefreshLayout != null) {
            mSwipeRefreshLayout.setRefreshing(true);
        }
    }

    @Override
    public void hideRefreshProgress() {
        if (mSwipeRefreshLayout != null && mSwipeRefreshLayout.isRefreshing()) {
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }

    @Override
    public void setPresenter(@NonNull HotPickContract.Presenter presenter) {
        this.mHotPickPresenter = presenter;
    }
}
